from datetime import datetime
from json import load
from random import choice
from re import search
from time import time
from django.contrib.auth.hashers import make_password, check_password
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.core.cache import cache
from django_redis import get_redis_connection
from app.models import User, messageTable, BackgroundMusic, Message
from learningPlanet.models import CollectTable, JudgeTable, Blog, Tag, Recommend, Category
from link.views import get_friend_links
from log.models import RequestLogTable
from myTool.messageService import returnRandomCode, returnMessageSurviceStatus
from myTool.tools import base64ToPicture, str_to_timestamp
# 在登录中往往都需要使用post请求，在使用该请求是，需要进行csrf_token的验证，通过该验证有3中方法
'''
1.在settings的MIDDLEWARE中注释掉csrf验证的中间件
2.在模板的form表单中添加{%csrf_token%}
3.使用装饰器获取豁免权:在视图函数的上一行使用装饰器:@csrf_exempt
'''


# 新增通知
def addMessage(senderId, receiverId, content):
    messageTable(receiverId_id=receiverId, senderId=senderId, content=content).save()


# 判断是否处于登录状态
def isLoginStatus(request):
    try:
        userId = request.get_signed_cookie('userId', salt='LLL')  # 从cookie中获取用户的id
        status = cache.get(userId)  # 再从缓冲中获取用户的登录状态
        return status, userId
    except:
        return None, None


# 缓存的使用 登录
@cache_page(timeout=60, cache='default')  # timeout指定缓存过期时间,cache指定缓存用的数据库，
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')

    if request.method == 'POST':
        account = request.POST.get('account')
        password = request.POST.get('password')
        user = User.get_by_username_and_mobile(account, account)
        response = render(request, 'login.html', context=locals())
        script_str = '''<script>popMsg(`<div id="msg-top">提示
            <span class="iconfont close" id="closeMsg">&#xe61a;</span>
            </div><div id="msg-bottom">{}</div>`);</script>'''
        if not user:
            response.write(script_str.format('该账号还未注册~'))
            response.flush()
            return response

        if not check_password(password, user.password):  # 参数顺序:明文 密文
            response.write(script_str.format('密码错误~'))
            response.flush()
            return response

        # 缓存的实现的内部原理:接受到来自客户端的要求后，服务器不是首先到数据库请求数据，而是查看是否有该数据的
        # 缓存，如果有，则直接返回缓存中的数据，如果没有，则再请求数据库同时创建相应的缓存
        # 使用缓存保存用户的登录状态 同时设置cookie记录用户的登录状态
        # 当用户进行的某项操作需要登录后才能使用时,同时检验客户端(cookie)和服务端(cache),以确保操作的安全性
        # 登录成功后重定向到首页
        response = redirect(reverse('app:index')) #TODO redirect by refer link
        response.set_signed_cookie('userId', user.id, salt='LLL', max_age=7 * 24 * 60 * 60)  # 设置加密的cookie
        cache.set(str(user.id), 'true', timeout=7 * 24 * 60 * 60)  # 同时将登录信息保存在缓存中
        return response


# 注册
@cache_page(timeout=60, cache='default')
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')

    if request.method == 'POST':

        redis_con = get_redis_connection('default')  # 连接redis
        telValue = request.POST.get('tel')  # 用户的手机号码
        yzmValue = request.POST.get('yzm')  # 验证码
        pwdValue = request.POST.get('pwd')  # 密码

        # 检查验证码是否正确
        try:
            code = str(redis_con.get(str(telValue) + 'code'), encoding='utf8')  # 存在本地的验证码
        except:
            code = ''
        forgetPwd = request.POST.get('forgetPwd')

        if yzmValue == code:
            if forgetPwd:  # 如果是进行密码修改就不需要更新用户名
                user = User.get_by_mobile(telValue)
                User.update_user(user, user.mobile, user.username, pwdValue, False)  # 更新user
                return JsonResponse({'msg': '密码修改成功!'})

            # 注册
            user = User.create_user(telValue, pwdValue, telValue, False)

            # 通知
            content = f'亲爱的{user.username}:<br>欢迎来到0318-SPACE,在这里,博主会不定期更博客,学习心得,知识点等等,和大家一起学习,' \
                      f'如果您也想在本站发布,只需提交申请理由后,待管理员授权即可。欢迎大家积极申请!!!<br><br><br>&nbsp;&nbsp;&nbsp;' \
                      f'&nbsp;&nbsp;&nbsp;---LLL'
            addMessage(1, user.id, content)
            return JsonResponse({'msg': '注册成功,可以直接登录!'})
        else:
            return JsonResponse({'msg': '验证码错误!'})


# 发送验证码
def sendCode(request):
    if request.method == 'POST':
        redis_con = get_redis_connection('default')  # 连接redis
        telValue = request.POST.get('tel')  # 用户的手机号码
        forgetPwd = request.POST.get('forgetPwd')
        isRegister = User.get_by_mobile(telValue)  # 匹配该手机号是否已经注册

        # 如果是忘记密码，但是该账号还未注册
        if forgetPwd and not isRegister:
            return JsonResponse({'msg': '该号码还未注册!'})

        # 如果是注册，但是该账号已被注册
        if not forgetPwd and isRegister:
            return JsonResponse({'msg': '该号码已注册,可以直接登录!'})

        # 没有注册就发送验证码
        code = returnRandomCode()  # 随机验证码
        messageSurviceStatus = returnMessageSurviceStatus(phoneNumber=telValue, code=code)  # 发送
        redis_con.setex(str(telValue) + 'code', 300, code)  # 保存当前手机号码的验证码 时效5分钟
        if messageSurviceStatus:
            return JsonResponse({'msg': '验证码已发送至您的手机,请注意查收!'})
        else:
            return JsonResponse({'msg': '验证码发送失败!'})


# 访问出错
def error(request):
    return render(request, '404.html')


# 首页和学习星球的公共数据
def common_data():
    author = 'LLL'
    blogNum = Blog.get_all().count()  # 博客数量
    startTime = str_to_timestamp('2021-5-20 00:00:00')
    birthday = '2021-5-20'
    days = int((time() - startTime) / (3600 * 24))  # 运行的天数
    todayObj = datetime.now()
    toyear, tomonth, today = todayObj.year, todayObj.month, todayObj.day
    visitorNum = RequestLogTable.get_views()  # 访客量
    visitorNumToday = RequestLogTable.get_views(toyear, tomonth, today)  # 今日访客量

    # 排行榜
    with open('data/data.json', 'r', encoding='utf8') as f:
        conDic = load(f)
        resTopDay = conDic['day'][:5]
        resTopMonth = conDic['month'][:5]
        resTopWeek = conDic['week'][:5]

    # 友链
    link_list = get_friend_links()

    # 获取背景音乐
    music_list = BackgroundMusic().get_all()

    # 获取标签
    tag_list = Tag().get_all()

    # 获取推荐
    recommend_list = Recommend().get_all()

    # 获取分类
    category_list = Category().get_all()

    # 获取留言
    message_list = Message().get_all()

    return locals()


# 博客首页
# @cache_page(timeout=60, cache='default')  # timeout指定缓存过期时间,cache指定缓存用的数据库
def index(request):
    if request.method == 'GET':
        LoginStatus, userId = isLoginStatus(request)  # 如果是登录状态则显示个人中心
        try:
            isManage = User.get_by_id(id=userId).is_superuser
        except:
            isManage = ''

        # 分页
        blogObjList = []
        blogs = Blog.get_all()
        paginator = Paginator(blogs, 10)  # 创建分页对象，每页10条数据
        page_num = request.GET.get('page', '1')  # 获取页码，如果没有获取到则默认为1
        try:
            page = paginator.page(page_num)  # 获取某一页的数据
        except(PageNotAnInteger, EmptyPage, InvalidPage):
            page = paginator.page('1')  # 发生错误跳转到第一页

        for blogObj in page.object_list:

            conDic = {
                'title': blogObj.title,
                'createdTime': str(blogObj.createdTime).split(' ')[0],
                'author': blogObj.author.username,
                'category': blogObj.category.title,
                'summary': blogObj.summary,
                'blogId': blogObj.id,
                'total_views': blogObj.total_views,
                'total_likes': blogObj.total_likes,
                'total_collect': blogObj.total_collect,
                'total_judge': JudgeTable().get_judge_count_by_blog_id(blogObj.id),
                'isTop': blogObj.isTop
            }

            # 匹配背景图片
            background = search(r'<img.*?src="(.*?)".*?>', blogObj.content)
            if background:
                background = background.group(1) #使用匹配到的第一个图片
            else:
                background = '../media/imgs/bg_preview.png'
            conDic.update({'background': background})
            blogObjList.append(conDic)

        context = locals()
        context.update(common_data())

        return render(request, 'index.html', context=context)


# 个人中心
def personalCenter(request, userId):
    LoginStatus, userId = isLoginStatus(request)  # 如果是登录状态则显示个人中心
    if not LoginStatus:  # 没有登录就直接跳转到首页
        return redirect(reverse('app:index'))

    if request.method == 'GET':
        user = User.get_by_id(userId)
        isManager = user.is_superuser  # 查看该用户是否是管理者
        isVistor = 1 if user.isVistor else ''  # 是否是游客

        blogObj = Blog.objects.all()
        blogNum = blogObj.count()  # 博客数量

        # 返回个人的收藏记录的数据
        collectList = []
        collectObjs = CollectTable.objects.filter(Q(collectorId_id=userId) & Q(isCollected=1))[:12]
        if collectObjs:
            Num = 1
            for collectObj in collectObjs:
                conDic = {
                    'id': Num,
                    'blogName': collectObj.blogId.title,
                    'blogId': collectObj.blogId.id,
                    'blogAuthor': collectObj.collectorId.username,
                    'blogAuthorId': collectObj.collectorId.id,
                    'collectTime': str(collectObj.collectTime),
                    'summary': collectObj.blogId.summary.replace('&nbsp;', '')[:50]
                }

                if len(conDic['blogName']) > 10:
                    conDic['blogName'] = conDic['blogName'][:10] + '...'
                Num += 1
                collectList.append(conDic)

        # 返回博客的内容
        blogList = []
        if isManager:  # 只有是管理者才可能发表了博客
            allNum = Blog.objects.filter(author_id=userId).count()
            blogObjs = Blog.objects.filter(Q(author_id=userId) & Q(isShow=1))[:12]  # 最多10条博客内容
            blogN = 1
            for blogObj in blogObjs:
                conDic = {
                    'id': blogN,
                    'blogId': blogObj.id,
                    'blogName': blogObj.title,
                    'blogSummary': blogObj.summary,
                    'blogCreateTime': str(blogObj.createdTime).split(' ')[0],
                    'blogUpdateTime': str(blogObj.updatedTime).split(' ')[0],
                    'blogCategory': blogObj.category,
                    'blogTags': blogObj.tags.replace('LLL', ' '),
                    'blogViews': blogObj.total_views,
                    'blogLikes': blogObj.total_likes,

                }
                if len(conDic['blogSummary']) > 26:
                    conDic['blogSummary'] = conDic['blogSummary'][:23] + '...'
                blogN += 1
                blogList.append(conDic)

        if userId == '1':  # 只有我才能看到的数据
            # 返回用户的数据
            userList = []
            userObjs = User.objects.all()
            userNum = 1
            for userObj in userObjs:
                degree = '管理员' if userObj.is_superuser else '普通用户'
                mobile = userObj.mobile if not userObj.isVistor else '未绑定'
                blogNum = Blog.objects.filter(author_id=userObj.id).count()
                conDic = {
                    'userNum': userNum,
                    'userId': userObj.id,
                    'username': userObj.username,
                    'degree': degree,  # 1代表管理员 空代代表普通用户
                    'mobile': mobile,  # 如果有手机号就说明绑定了手机
                    'joinTime': str(userObj.date_joined).split('.')[0],
                    'blogNum': blogNum  # 博客数量
                }
                userList.append(conDic)
                userNum += 1

        # 返回通知的数据
        messageUnreadList, messageReadList = returnMessage(userId)
        # 未读的通知数量
        unReadNum = len(messageUnreadList) if len(messageUnreadList) > 0 else ''

        return render(request, 'personalCenter.html', context=locals())


# 返回个人收藏的数据
def returnCollectList(request):
    LoginStatus, userId = isLoginStatus(request)  # 如果是登录状态则显示个人中心
    if not LoginStatus:  # 没有登录就直接跳转到首页
        return redirect(reverse('app:index'))

    if request.method == 'POST':
        nowId = request.POST.get('nowId')
        pre_next = nowId.split('-')[0]
        nowPage = int(nowId.split('-')[1])
        if pre_next == 'pre':
            nowPage -= 1
        else:
            nowPage += 1

        if nowPage < 0:
            nowPage = 0

        collectObjs = CollectTable.objects.filter(Q(collectorId_id=userId) & Q(isCollected=1))[
                      nowPage * 12: nowPage * 12 + 12]
        collectList = []
        if collectObjs:
            Num = nowPage * 12 + 1
            for collectObj in collectObjs:
                conDic = {
                    'id': Num,
                    'blogName': collectObj.blogId.title,
                    'blogId': collectObj.blogId.id,
                    'blogAuthor': collectObj.collectorId.username,
                    'blogAuthorId': collectObj.collectorId.id,
                    'collectTime': str(collectObj.collectTime),
                    'summary': collectObj.blogId.summary[:50]
                }
                if len(conDic['blogName']) > 15:
                    conDic['blogName'] = conDic['blogName'][:15] + '...'
                Num += 1
                collectList.append(conDic)
        preId = 'pre-' + str(nowPage)
        nextId = 'next-' + str(nowPage)
        return JsonResponse({'dataList': collectList, 'preId': preId, 'nextId': nextId})


# 退出登录
def logout(request, userId):
    cache.set(userId, '0')
    response = redirect(reverse('app:index'))
    response.delete_cookie('userId')
    response.flush()
    return response


# 修改头像
def modifyAvatar(request):
    LoginStatus, userId = isLoginStatus(request)  # 如果是登录状态则显示个人中心
    if not LoginStatus:  # 没有登录就直接跳转到首页
        return redirect(reverse('app:index'))
    wordList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
    if request.method == 'POST':
        try:
            userId = request.POST.get('userId')
            imgData = request.POST.get('imgData')
            avatarPath = base64ToPicture(dataList=[imgData], title=choice(wordList) + str(userId) + choice(wordList),
                                         path='static/avatar/')[0]
            user = User.get_by_id(userId)
            user.avatar = avatarPath
            user.save()
            return JsonResponse({'msg': '头像修改成功!'})
        except:
            return JsonResponse({'msg': '头像修改失败!'})


# 修改个人资料
def modifyDesc(request):
    LoginStatus, userId = isLoginStatus(request)  # 如果是登录状态则显示个人中心
    if not LoginStatus:  # 没有登录就直接跳转到首页
        return redirect(reverse('app:index'))

    if request.method == 'POST':
        userId = request.POST.get('userId')
        user = User.get_by_id(userId)
        if user:
            name = request.POST.get('name')
            isExistName = User.get_by_username(name)
            if isExistName and name != user.username:  # 如果新用户名存在就不能进行用户名的修改
                user.save()
                return JsonResponse({'msg': '该用户名已经存在'})
            whichId = request.POST.get('whichId')  # which=0代表修改名称 1代表修改职位 2代表修改个人简介
            if whichId == '0':
                user.username = name
            elif whichId == '1':
                job = request.POST.get('job')
                user.job = job
            elif whichId == '2':
                desc = request.POST.get('desc')
                user.desc = desc
            user.save()
            return JsonResponse({'msg': '修改成功'})
        else:
            return JsonResponse({'msg': '修改失败'})


# 游客登录
def visitor(request):
    # 生成一个随机用户名和手机号(假的)
    nowTimeStamp = str(time()).replace('.', '')[6:]
    user = User.create_user(mobile=nowTimeStamp, password=nowTimeStamp, username=nowTimeStamp, isVistor=True)
    response = redirect(reverse('app:personalCenter', kwargs={'userId': user.id}))
    response.set_signed_cookie('userId', user.id, salt='LLL', max_age=7 * 24 * 60 * 60)  # 设置加密的cookie
    cache.set(str(user.id), 'true', timeout=7 * 24 * 60 * 60)  # 同时将登录信息保存在缓存中
    senderId = 1
    receiverId = user.id
    content = f'亲爱的{user.username}:<br>欢迎来到0318-SPACE,在这里,博主会不定期更博客,学习心得,知识点等等,和大家一起学习,' \
              f'如果您觉得本站不错,打算长期入驻本站,可以进行注册/绑定手机。欢迎您的到来!!!(您当前的账号的密码为:{make_password(nowTimeStamp)})<br><br><br>&nbsp;&nbsp;&nbsp;' \
              f'&nbsp;&nbsp;&nbsp;---&nbsp;LLL'

    addMessage(senderId, receiverId, content)
    return response


# 返回个人博客的数据
def returnBlogList(request):
    LoginStatus, userId = isLoginStatus(request)  # 如果是登录状态则显示个人中心
    if not LoginStatus:  # 没有登录就直接跳转到首页
        return redirect(reverse('app:index'))

    if request.method == 'POST':
        nowId = request.POST.get('nowId')
        pre_next = nowId.split('-')[0]
        nowPage = int(nowId.split('-')[1])
        if pre_next == 'pre':
            nowPage -= 1
        else:
            nowPage += 1

        if nowPage < 0:
            nowPage = 0

        # 返回个人博客的数据
        blogList = []
        blogObjs = Blog.objects.filter(Q(author_id=userId) & Q(isShow=1))[
                   nowPage * 12: nowPage * 12 + 12]
        if blogObjs:
            Num = nowPage * 12 + 1
            for blogObj in blogObjs:
                conDic = {
                    'id': blogObj.id,
                    'blogId': blogObj.id,
                    'blogName': blogObj.title,
                    'blogSummary': blogObj.summary,
                    'blogCreateTime': str(blogObj.createdTime).split(' ')[0],
                    'blogUpdateTime': str(blogObj.updatedTime).split(' ')[0],
                    'blogCategory': blogObj.category.title,
                    'blogTags': blogObj.tags.replace('LLL', ' '),
                    'blogViews': blogObj.total_views,
                    'blogLikes': blogObj.total_likes,
                    'Num': Num,

                }
                if len(conDic['blogSummary']) > 26:
                    conDic['blogSummary'] = conDic['blogSummary'][:23] + '...'

                blogList.append(conDic)
                Num += 1

        preId = 'pre-' + str(nowPage)
        nextId = 'next-' + str(nowPage)
        return JsonResponse({'dataList': blogList, 'preId': preId, 'nextId': nextId})


# 删除博客
def deleteBlog(request):
    LoginStatus, userId = isLoginStatus(request)  # 如果是登录状态则显示个人中心
    if not LoginStatus:  # 没有登录就直接跳转到首页
        return redirect(reverse('app:index'))

    blogId = request.POST.get('blogId')
    try:
        blogObj = Blog.objects.filter(id=blogId).first()
        blogObj.isShow = 0
        blogObj.save()
        return JsonResponse({'msg': '删除成功!'})
    except:
        return JsonResponse({'msg': '删除失败!'})


# 申请为管理
def applyManage(request):
    if request.method == 'POST':
        userId = request.POST.get('userId')  # 发送人的id
        content = request.POST.get('applyReason')  # 发送的内容
        applyObj = messageTable()
        applyObj.senderId = userId
        applyObj.receiverId_id = 1  # 发送给我
        applyObj.content = content
        applyObj.save()
        return JsonResponse({'msg': '您的申请提交成功,待管理员审核后,我们会将审核结果第一时间通知您!'})


# 博主的介绍
def descBloger(request):
    if request.method == 'POST':
        userId = request.POST.get('userId')
        bloger = User.get_by_id(userId)
        username = bloger.username
        job = bloger.job
        desc = bloger.desc
        avatar = bloger.avatar
        userId = bloger.id
        isManager = 1 if bloger.is_superuser else ''
        conDic = {
            'username': username,
            'job': job,
            'desc': desc,
            'avatar': str(avatar),
            'isManager': isManager,
            'userId': userId
        }
        return JsonResponse(conDic)
    return JsonResponse({'msg': '请求异常!'})


# 为用户重新授权
def grantUser(request):
    if request.method == 'POST':
        degree = request.POST.get('degree')
        userId = request.POST.get('userId')
        userObj = User.get_by_id(userId)
        degree = 1 if degree == '管理员' else 0
        userObj.is_superuser = degree
        userObj.save()

        return JsonResponse({'msg': '授权成功!'})
    return JsonResponse({'msg': '授权失败!'})


# 删除用户
def deleteUser(request):
    if request.method == 'POST':
        userId = request.POST.get('userId')
        userObj = User.get_by_id(userId)
        userObj.delete()

        return JsonResponse({'msg': '删除成功!'})
    return JsonResponse({'msg': '删除失败!'})


# 返回会当前用户的通知信息
def returnMessage(userId):
    messageReadList = []
    messageUnreadList = []
    messageObjs = messageTable.objects.filter(Q(receiverId_id=userId) & Q(isShow=True))
    for messageObj in messageObjs:
        # 如果已读的信息大于30天没有删除 就自动删除
        # 2021-07-06 15:59:09.813004
        if messageObj.isRead and time() - str_to_timestamp(
                str(messageObj.messageTime).split('.')[0]) > 30 * 24 * 60 * 60:
            messageObj.isShow = False
            messageObj.save()

        isnobody = 1
        try:
            senderName = User.get_by_id(messageObj.senderId).username
            isnobody = ''
        except:
            senderName = '匿名'

        conDic = {
            'senderId': messageObj.senderId,
            'senderName': senderName,
            'sendTime': str(messageObj.messageTime).split('.')[0],
            'content': messageObj.content,
            'nobody': isnobody,  # 用于判断是否是匿名
            'messageId': messageObj.id
        }
        if messageObj.isRead:

            messageReadList.append(conDic)
        else:
            messageUnreadList.append(conDic)

    messageUnreadList.reverse()
    messageReadList.reverse()

    return messageUnreadList, messageReadList


# 返回通知的数据
def returnMessageData(request):
    if request.method == 'POST':
        userId = request.POST.get('userId')
        isRead = request.POST.get('isRead')
        messageUnreadList, messageReadList = returnMessage(userId)
        # 未读的通知数量
        if str(isRead) == '0':
            return JsonResponse({'data': messageUnreadList})
        else:
            return JsonResponse({'data': messageReadList})  # 返回已读的


# 发送私信
def sendMessage(request):
    if request.method == 'POST':
        senderId = request.POST.get('senderId')
        receiverId = request.POST.get('receiverId')
        content = request.POST.get('content')
        messageTable(senderId=senderId, receiverId_id=receiverId, content=content).save()
        return JsonResponse({'msg': '您的私信已送达!'})
    return JsonResponse({'msg': '您的私信发送失败!'})


# 标记为已读
def markMessage(request):
    if request.method == 'POST':
        messageId = request.POST.get('messageId')
        messageObj = messageTable.objects.filter(id=messageId).first()
        messageObj.isRead = 1
        messageObj.save()
        return JsonResponse({'msg': '操作成功!'})
    return JsonResponse({'msg': '操作失败!'})


# 删除通知
def deleteMessage(request):
    if request.method == 'POST':
        messageId = request.POST.get('messageId')
        messageObj = messageTable.objects.filter(id=messageId).first()
        messageObj.isShow = 0
        messageObj.save()
        return JsonResponse({'msg': '操作成功!'})
    return JsonResponse({'msg': '操作失败!'})


# 绑定手机
def bandMobile(request):
    if request.method == 'POST':
        # 如果没有注册就发送验证码到手机 15623108273
        userId = request.POST.get('userId')
        mobile = request.POST.get('tel')
        yzm = request.POST.get('yzm')

        # 检查验证码是否正确
        redis_con = get_redis_connection('default')  # 连接redis
        try:
            code = str(redis_con.get(str(mobile) + 'code'), encoding='utf8')  # 存在本地的验证码
        except:
            code = ''
        if yzm == code:
            user = User.get_by_id(userId)
            user.mobile = mobile
            user.isVistor = False
            user.save()
            return JsonResponse({'msg': '绑定成功!'})
        else:
            return JsonResponse({'msg': '验证码错误!'})


# 忘记密码
def forgetPwd(request):
    if request.method == 'GET':
        return render(request, 'forgetPwd.html', context=locals())


# 保存用户的留言
def savemessage(request):
    userId = request.POST.get('userId')
    content = request.POST.get('content')
    messageObj = Message(user_id=userId, content=content)
    messageObj.save()

    conDic = {
        'name': str(messageObj.user),
        'avatar': str(messageObj.user.avatar),
        'content': messageObj.content,
        'date': ''.join(str(messageObj.date).split('.')[:-1])
    }

    return JsonResponse(conDic)


# 用于测试
def test(request):
    return render(request, 'index.html')
